package org.leetcode.easy;

import org.junit.Test;

// Excel表列名称
public class ConvertToTitle {
    private String convertToTitle(int columnNumber) {
        StringBuilder stringBuilder = new StringBuilder();
        if (columnNumber <= 26) {
            return String.valueOf((char) (64 + columnNumber));
        } else {
            int number;
            while (true) {
                if ((number = columnNumber % 26) == 0) {
                    stringBuilder.append("Z");
                    if ((columnNumber = (columnNumber / 26) - 1) <= 26) {
                        stringBuilder.append((char) (64 + columnNumber));
                        return stringBuilder.reverse().toString();
                    }

                } else {
                    stringBuilder.append((char) (64 + number));
                    if ((columnNumber = (columnNumber / 26)) <= 26) {
                        stringBuilder.append((char) (64 + columnNumber));
                        return stringBuilder.reverse().toString();
                    }
                }
            }
        }
    }
    // leetcode官方题解
    public String convertToTitleTwo(int columnNumber) {
        StringBuffer sb = new StringBuffer();
        while (columnNumber > 0) {
            int a0 = (columnNumber - 1) % 26 + 1;
            sb.append((char) (a0 - 1 + 'A'));
            columnNumber = (columnNumber - a0) / 26;
        }
        return sb.reverse().toString();
    }

    @Test
    public void test() {
        System.out.println(convertToTitle(26));
        System.out.println(convertToTitle(701));
    }
}
